package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.*;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @RequestMapping("/list")
    @RequiredPermission(name = "角色查询", expression = "role:list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "role/list";
    }
    @RequestMapping("/delete")
    @RequiredPermission(name = "角色删除", expression = "role:delete")
    public String delete(Long id) {
       roleService.delete(id);
        return "redirect:/role/list";
    }

    @RequestMapping("/input")
    @RequiredPermission(name = "角色新增或修改", expression = "role:input")
    public String input(Model model, Long id) {
        if (id !=null) {
            Role role = roleService.get(id);
            model.addAttribute("role",role);
       List<Permission> myPermissions = permissionService.queryByRoleId(role.getId());
            model.addAttribute("myPermissions", myPermissions);

        }
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions", permissions);



        return "role/input";
    }
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "角色新增或修改", expression = "role:saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] permissionIds) {
        System.out.println(permissionIds);
        if (role.getId()==null){
            roleService.save(role,permissionIds);
        }else{
            roleService.update(role,permissionIds);
        }
        return "redirect:/role/list";
    }


}
